//
//  HJZStatusContentViewController.m
//  HJZWeiBo
//
//  Created by 蒋晨成 on 16/6/2.
//  Copyright © 2016年 蒋晨成. All rights reserved.
//

#import "HJZStatusContentViewController.h"
#import "UIBarButtonItem+Extend.h"
#import "HJZStatusTopView.h"
#import "HJZStatusCommentToolBar.h"
#import "HJZComment.h"
#import "HJZCommentFrame.h"
#import "HJZCommentTableViewCell.h"
#import "HJZCommentBottomToolBar.h"
#import <MJRefresh.h>
#import "HJZUploadViewController.h"
#import "MeDefaultViewController.h"

@interface HJZStatusContentViewController ()<UITableViewDelegate, UITableViewDataSource, HJZStatusCommentToolBarDelegate,WBHttpRequestDelegate, HJZCommentButtonToolBarDelegate, HJZRetweenStatusViewDelegate, HJZStatusTopViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@property (nonatomic, strong) UIView *moveView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) NSString *since_id;

@end

@implementation HJZStatusContentViewController

#pragma mark --- 微博SDK请求用户信息 ---
- (void)requestForUserProfileWithUserName:(NSString *)name
{
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    
    
    
    [WBHttpRequest requestForUserProfile:nil withAccessToken:accessToken andOtherProperties:@{@"screen_name":name} queue:nil withCompletionHandler:^(WBHttpRequest *httpRequest, id result, NSError *error) {
        
        WeiboUser *user = (WeiboUser *)result;
        
        MeDefaultViewController *meDefaultVC = [[MeDefaultViewController alloc] init];
        meDefaultVC.user = user;
        [self.navigationController pushViewController:meDefaultVC animated:YES];
        
    }];
}



- (void)requestCommentData {
    
    NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"accessToken"];
    NSString *page = [NSString stringWithFormat:@"%ld", _page];
    [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/comments/show.json" httpMethod:@"GET" params:@{@"access_token":accessToken,@"id":_statusFrame.status.idstr, @"page":page,@"since_id":_since_id} delegate:self withTag:@"微博评论"];
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithDataResult:(NSData *)data {
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray *comments = dic[@"comments"];
    if (comments.count == 0) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    if (_page == 1) {
        [self.dataSource removeAllObjects];
    }
    
    for (NSDictionary *commentDic in comments) {
        HJZComment *comment = [[HJZComment alloc] init];
        [comment setValuesForKeysWithDictionary:commentDic];
      
      
        
        HJZCommentFrame *commentFrame = [[HJZCommentFrame alloc] init];
        commentFrame.comment= comment;
        [_dataSource addObject:commentFrame];

    }
   
    [self.tableView reloadData];
    self.tableView.mj_header.hidden = NO;
    self.tableView.mj_footer.hidden = NO;
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _page = 1;
    _since_id = @"0";
    
    self.navigationItem.title = @"微博正文";
    self.navigationController.navigationBar.tintColor = [UIColor blackColor];
    self.tabBarController.tabBar.hidden = YES;
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"<返回"style:UIBarButtonItemStylePlain target:self action:@selector(leftBarButtonAction:)];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
   UIBarButtonItem *rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_more" highImageName:@"navigationbar_more_highlighted" target:self action:@selector(rightBarButtonAction:)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
   
    
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [self setTableViewheadView];
    self.dataSource = [NSMutableArray array];
    [self requestCommentData];
    
    HJZCommentBottomToolBar *toolBar = [[HJZCommentBottomToolBar alloc]initWithFrame:CGRectMake(0, kHeight - 39 - 64, kWidth, 41)];
    toolBar.delegate = self;
    [self.view addSubview:toolBar];
    
    
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 1;
        self.since_id = @"0";
        [self requestCommentData];
        
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page++;
        HJZCommentFrame *commentFrame = _dataSource.lastObject;
        _since_id = commentFrame.comment.created_at;
        [self requestCommentData];
    }];
    self.tableView.mj_header.hidden = YES;
    self.tableView.mj_footer.hidden = YES;
    
}


- (void)commentButtonToolBarClickActionWithButtonTitle:(NSString *)string {
    if ([string isEqualToString:@"评论"]) {
        
        HJZUploadViewController *uploadVC = [[HJZUploadViewController alloc] init];
        uploadVC.status = _statusFrame.status;
        uploadVC.uploadType = UploadTypeComment;
        UINavigationController *createCommentNav = [[UINavigationController alloc] initWithRootViewController:uploadVC];
        
        [self.navigationController presentViewController:createCommentNav animated:YES completion:nil];
        
    }else if ([string isEqualToString:@"转发"]) {
        
        HJZUploadViewController *uploadVC = [[HJZUploadViewController alloc] init];
        uploadVC.status = _statusFrame.status;
        uploadVC.uploadType = UploadTypeRetween;
        UINavigationController *createCommentNav = [[UINavigationController alloc] initWithRootViewController:uploadVC];
        
        [self.navigationController presentViewController:createCommentNav animated:YES completion:nil];
        
    }
}

/**
 *  导航栏点击方法
 *
 */

- (void)leftBarButtonAction:(UIBarButtonItem *)barButton {
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)rightBarButtonAction:(UIBarButtonItem *)barButton {

}

/**
 *  tabelView代理
 *
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJZCommentTableViewCell *cell = [HJZCommentTableViewCell cellWithTableView:tableView];
    
    cell.commentFrame = _dataSource[indexPath.row];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HJZStatusCommentToolBar *toolBar = [[HJZStatusCommentToolBar alloc] init];
    toolBar.delegate = self;
    toolBar.status = _statusFrame.status;
    return toolBar;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    HJZCommentFrame *commentFrame = _dataSource[indexPath.row];
    
    
    return commentFrame.cellHeight + 10;
}


/**
 *  点击上方工具条代理方法
 *
 */

- (void)statusCommentToolBarClickWithButtonTag:(NSInteger)tag {
    if (tag == 0 ) {
        NSLog(@"转发");
    }else if (tag == 1) {
        NSLog(@"评论");
    }else {
        NSLog(@"赞");
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/**
 *  设置表头
 *
 */
- (void)setTableViewheadView {
    HJZStatusTopView *topView = [[HJZStatusTopView alloc] initWithFrame:_statusFrame.originalViewF];
    topView.delegate = self;
    topView.retweetView.delegate = self;
    topView.statusFrame = _statusFrame;
    self.tableView.tableHeaderView = topView;
}


#pragma mark -转发微博视图的代理方法 （RCLabel）
- (void)retweenStatusViewClickWithUrl:(NSString *)url {
    
    [self getRClabelWithUrl:url];
}

#pragma mark -微博的代理方法
- (void)statusTopViewClickWithUrl:(NSString *)url {
    [self getRClabelWithUrl:url];
}


/**
 *  RCLabel
 */
- (void)getRClabelWithUrl:(NSString *)url{
    NSString *content = url;
    if ([content hasPrefix:@"@"]) {
        content = [content stringByReplacingOccurrencesOfString:@"@" withString:@""];
        
        [self requestForUserProfileWithUserName:content];
        
    }else if ([content hasPrefix:@"#"]) {
        content = [content stringByReplacingOccurrencesOfString:@"#" withString:@""];
    }else if ([content hasPrefix:@"http"]){
        
    }
}

#pragma mark -微博代理方法 tap


- (void)statusTopViewTapWithRetweenStatus:(HJZStatus *)status {
    HJZStatusFrame *statusFrame = [[HJZStatusFrame alloc] init];
    statusFrame.status = status;
    HJZStatusContentViewController *statusContentVC = [[HJZStatusContentViewController alloc] init];
    statusContentVC.statusFrame = statusFrame;
    [self.navigationController pushViewController:statusContentVC animated:YES];
}
#pragma mark -微博代理方法 点击昵称
- (void)statusTopViewClickWithName:(NSString *)name {
    [self requestForUserProfileWithUserName:name];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
